import { useState, useEffect } from 'react';
import { message } from 'antd';
import { ProFormUploadButton } from '@ant-design/pro-form';
import { UploadFile, DeleteFile } from '@/services/upload';

export default (props: any) => {
  const { title, initFileList, maxCount } = props;

  const [uploadedFileList, handleUploadedFileList] = useState([]);

  useEffect(() => {
    if (initFileList) {
      handleUploadedFileList(initFileList);
    }
    console.log('effect');
  }, [initFileList]);

  const handleChange = async ({ fileList }: any) => {
    handleUploadedFileList(fileList);
  };

  const uploadFile = async ({ onSuccess, onError, file }: any) => {
    try {
      console.log('upload file');
      const response = await UploadFile('illuminant', file);

      file.fid = response.data.fid;
      onSuccess(response, file);
    } catch (e) {
      onError(e);
    }
  };

  const removeFile = async (file: any) => {
    console.log('remove file');
    const response = await DeleteFile(file.fid);
    if (response.code === 10000) message.success('删除文件成功');
    else message.error('文件删除失败');
  };

  const uploadProps = {
    name: 'file',
    title,
    fileList: uploadedFileList,
    fieldProps: {
      maxCount,
      customRequest: uploadFile,
      onRemove: removeFile,
    },
  };

  return <ProFormUploadButton {...uploadProps} onChange={handleChange} />;
};
